<?php

namespace app\admin\controller\ykjp\purchase;

use app\common\controller\Backend;

/**
 * 采购订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend {

    /**
     * Order模型对象
     * @var \app\admin\model\ykjp\purchase\Order
     */
    protected $model = null;
    protected $distinguish = true;
    protected $wherename = "";
    protected $searchFields = "name";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\purchase\Order;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        // $this->view->assign("storageList", $this->model->getStorageList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $storageModel = new \app\admin\model\ykjp\purchase\Storage;
            $this->searchFields = "supplier.name,order.code";
            $this->wherename = "order.firmid";
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('supplier')->visible(['name']);
                $row['storageNums'] = 0;
                if ($row['status'] == 2) {
                    $row['storageNums'] = $storageModel->where('purchase_id', $row['id'])->where("status", "3")->sum('totalNums');
                }
                if ($row['status'] == 3) {
                    $row['storageNums'] = $row['totalNums'];
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看订单详情
     */
    public function orderDetail($ids) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $detail = $this->model
                ->where($where)
                ->order($sort, $order)
                ->where("id", $ids)
                ->select();
        $productModel = new \app\admin\model\ykjp\purchase\Product;
        $product = $productModel->with(['products'])->where("purchase_id", $ids)->select();
        $arr;
        if ($product) {
            foreach ($product as $key => $value) {
                $a = json_decode($value['products']['prop']);
                $value['products']['prop'] = $this->model->object_array($a);

                $arr[] = $value;
            }
        }
        $storageMode = new \app\admin\model\ykjp\purchase\Storage;
        $isCount = $storageMode->where("firmid", $this->auth->firmid)->where("purchase_id", $ids)->count();
        $this->assign("detail", $detail);
        $this->assign("product", $product);
        $this->assign("isCount", $isCount);
        return $this->view->fetch("detail");
    }

    /**
     * 编辑
     */
    public function edit($ids = null) {

        if ($this->request->isAjax()) {
            $type = $this->request->param("type");
            if ($type == 1) {
                
            } else {
                if ($ids == null) {
                    $this->error(__('fail'));
                }
                $product = $this->request->param("product/a");
                $row = $this->request->param("row/a");
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $isRset = $this->model
                        ->where("firmid", $this->auth->firmid)
                        ->where("id", $ids)
                        ->select();
                $supperModel = new \app\admin\model\ykjp\information\basisinfo\Supplier;
                $supper = $supperModel->get(['id' => $row['supplier_id'], "firmid" => $this->auth->firmid]);
                if (!$isRset) {
                    $this->error(__('fail'));
                }
                if (isset($isRset[0]['status']) && $isRset[0]['status'] != 0) {
                    $this->error(__('not editable'));
                }
                $row['supplier'] = $supper["name"];
                $row['delivery_time'] = strtotime($row['delivery_time']);
                $row['billing_time'] = strtotime($row['billing_time']);
                $row['wait_nums'] = $row['totalNums'];
                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
                $row['updatetime'] = time();
                $dataRow = $this->model
                        ->where("id", $ids)
                        ->update($row);

                if (!$product) {
                    $this->error(__('Product cannot be empty'));
                }
                $product = json_decode($product[0]);
                $product = $this->model->object_array($product);
                $purchaseProduct = new \app\admin\model\ykjp\purchase\Product;
                $where = [];
                foreach ($product as $key => $val) {
                    $id = $val['data_id'];
                    unset($val["data_id"]);
                    $val['wait_nums'] = $val['nums'];
                    $val['updatetime'] = time();
                    if ($id) {
                        $up = $purchaseProduct->where("purchase_id", $ids)->where("firmid", $this->auth->firmid)->where("id", $id)->update($val);
                        $where[] = $id;
                    } else {
                        $val['purchase_id'] = $ids;
                        $val['createtime'] = time();
                        $val['firmid'] = $this->auth->firmid;
                        $inser = $purchaseProduct->insertGetId($val);
                        if ($inser) {
                            $where[] = $inser;
                        }
                    }
                }
                $deletTime['deletetime'] = time();
                $update = $purchaseProduct->where("purchase_id", $ids)->where("id", "not in", $where)->update($deletTime);
                // if($update){
                //     $this->success(null, null, ['result' =>"success" ]);
                // }
                if ($where) {
                    $this->success(null, null, ['result' => "success"]);
                } else {
                    $this->error(__("fail"));
                }
            }
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $detail = $this->model
                ->where($where)
                ->order($sort, $order)
                ->where("id", $ids)
                ->where("status", 0)
                ->select();
        if (!$detail) {
            $this->error(__('not editable'));
        }
        $productModel = new \app\admin\model\ykjp\purchase\Product;
        $product = $productModel->with(['products'])->where("purchase_id", $ids)->select();
        if ($product) {
            foreach ($product as $key => $value) {
                $a = json_decode($value['products']['prop']);
                $value['products']['prop'] = $this->model->object_array($a);
            }
        }
        $hosemModel = new \app\admin\model\ykjp\information\basisinfo\Warehouse;
        $hose = $hosemModel->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
        $this->assign("detail", $detail);
        $this->assign("hose", $hose);
        $this->assign("product", $product);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "") {
        if ($ids) {
            $data = $this->model->where("id", "in", $ids)->where("status", "0")->where("firmid", $this->auth->firmid)->select();
            if ($data) {
                $purchaseProduct = new \app\admin\model\ykjp\purchase\Product;
                $result = 0;
                foreach ($data as $key => $val) {
                    $del = $this->model->where("id", $val['id'])->where("firmid", $this->auth->firmid)->update(array("deletetime" => time()));
                    $result += $del;
                    if ($del) {
                        $purchaseProduct->where("purchase_id", $val['id'])->where("firmid", $this->auth->firmid)->update(array("deletetime" => time()));
                    }
                }
                if ($result) {
                    $this->success();
                }
            }

            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 反审核
     */
    public function Anti($ids = null) {
        if ($ids) {
            $data = $this->model->where("firmid", $this->auth->firmid)->where("status", "in", [1, 2])->where("id", $ids)->find();
            if ($data) {
                $purchaseProduct = new \app\admin\model\ykjp\purchase\Product;
                $result = 0;
                //只有未生成入库单的采购单才可以反审核
                $storageMode = new \app\admin\model\ykjp\purchase\Storage;
                $isCount = $storageMode->where("firmid", $this->auth->firmid)->where("purchase_id", $ids)->count();
                if ($isCount == 0) {
                    $updateData = array("updatetime" => time(), "status" => "0", "reason" => null);
                    $up = $this->model->where("id", $ids)->update($updateData);
                    if ($up) {
                        $updateData = array("updatetime" => time(), "status" => "0");
                        $upPorduct = $purchaseProduct->where("purchase_id", $ids)->update($updateData);
                        if ($upPorduct) {
                            $this->success(null, null, array("result" => "success"));
                        } else {
                            $up = $this->model->where("id", $ids)->update(array("updatetime" => time(), "status" => $data['status']));
                            $this->error(__("operate fail"));
                        }
                    }
                } else {
                    $this->error(__('Existing inbound order generation, not reverse audit'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 生成入库单
     */
    public function joinStorage($ids = null) {
        if ($ids) {
            $list = $this->model->where("id", $ids)->where("wait_nums", ">", 0)->find();
            $row = array();
            if ($list) {
                $row['purchase_id'] = $list['id'];
                $row['purchase_code'] = $list['code'];
                $row['supplier_id'] = $list['supplier_id'];
                $row['contact'] = $list['contact'];
                $row['phone'] = $list['phone'];
                $row['delivery_time'] = $list['delivery_time'];
                $row['billing_time'] = time();
                $row['the_way'] = $list['type'];
                $row['inbound_type'] = "0";
                $row['partition_id'] = $list['warehouse_partition_id'];
                $row['warehouse_id'] = $list['warehouse_id'];
                $row['city'] = $list['city'];
                $row['address'] = $list['address'];
                $row['status'] = "0";
                $row['remark'] = $list['remark'];
                $row['firmid'] = $list['firmid'];
                $row['totalNums'] = $list['wait_nums'];
                $row['money'] = $list['totalMoney'];
                $row['admin_id'] = $this->auth->id;
                $row['code'] = "YKS" . date("ymdHis", time()) . rand(1000, 9999);
                $row['createtime'] = time();
                $row['updatetime'] = time();
                $rate = $list['rate'] / 100 + 1;
                $storageModel = new \app\admin\model\ykjp\purchase\Storage;
                $purchaseProduct = new \app\admin\model\ykjp\purchase\Product;
                $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
                //开启事务
                $this->model->startTrans();
                $storageModel->startTrans();
                $purchaseProduct->startTrans();
                $stpModel->startTrans();

                $isnertResult = $storageModel->insertGetId($row);
                if ($isnertResult) {
                    $proList = $purchaseProduct
                            ->where('purchase_id', $ids)
                            ->where("wait_nums", ">", 0)
                            ->Field('product_id,price,wait_nums,nums,firmid,subtotal,remarks as remark,unit,id as purchase_proid')
                            ->select();
                    $totalMoney = 0;
//                    $totalNums=0;
                    if ($proList) {
                        $proList = collection($proList)->toArray();
                        $data = array();
                        foreach ($proList as $val) {
                            if ($val['wait_nums'] != $val['nums']) {
                                $val['subtotal'] = round($val['wait_nums'] * $val['price'], 2);
                                $totalMoney += $val['subtotal'];
//                              $totalNums=$val['wait_nums'];
                            }
                            $temp = $val;
                            $temp['nums'] = $val['wait_nums'];
                            unset($temp['wait_nums']);
                            $temp['warehouse_id'] = $list['warehouse_id'];
                            $temp['partition_id'] = $list['warehouse_partition_id'];
                            $temp['storage_id'] = $isnertResult;
                            $temp['inbound_type'] = "0";
                            $temp['status'] = "0";
                            $temp['createtime'] = time();
                            $temp['updatetime'] = time();
                            $data[] = $temp;
                        }
                        $result = $stpModel->insertAll($data);

                        if ($result) {
                            if ($totalMoney != 0) {
//                                $totalMoney = round($totalMoney * $rate, 2);
                                $upS = $storageModel->where("id", $isnertResult)->update(array("money" => $totalMoney));
                                if (!$upS) {
                                    $this->model->rollback();
                                    $storageModel->rollback();
                                    $purchaseProduct->rollback();
                                    $stpModel->rollback();
                                    $this->error(__('operate fail'));
                                }
                            }
                            //修改采购单的冻结数

                            $up = $this->model->where("id", $ids)->update(array("updatetime" => time(), "wait_nums" => 0));
                            if (!$up) {
                                $this->model->rollback();
                                $storageModel->rollback();
                                $purchaseProduct->rollback();
                                $stpModel->rollback();
                                $this->error(__('operate fail'));
                            }
                            $upPord = $purchaseProduct->where("purchase_id", $ids)->update(array("updatetime" => time(), "wait_nums" => 0));
                            if (!$upPord) {
                                $this->model->rollback();
                                $storageModel->rollback();
                                $purchaseProduct->rollback();
                                $stpModel->rollback();
                                $this->error(__('operate fail'));
                            }

                            $this->model->commit();
                            $storageModel->commit();
                            $purchaseProduct->commit();
                            $stpModel->commit();
                            $this->success(null, null, array("result" => "success"));
                        } else {
                            $this->model->rollback();
                            $storageModel->rollback();
                            $purchaseProduct->rollback();
                            $stpModel->rollback();
                            $this->error(__('operate fail'));
                        }
                    } else {
                        $this->error(__('No product results found'));
                    }
                }
                $this->model->rollback();
                $storageModel->rollback();
                $purchaseProduct->rollback();
                $stpModel->rollback();
                $this->error(__('operate fail'));
            }
            $this->error(__('No results found'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
